<template>
  <q-page>
    <div class="bg-grey-2 q-pa-md" v-if="data.rows.length">
      <div class="q-gutter-y-md">
        <template v-for="(row, index) in data.rows" :key="index">
          <q-card flat @click="open(row)">
            <q-item>
              <q-item-section>
                <q-item-label>
                  {{ row.title }}
                </q-item-label>
                <q-item-label caption>
                  {{ row.demandId }}
                </q-item-label>
              </q-item-section>
              <q-item-section side>
                <q-item-label
                  :class="`text-` + $store.state.common.colors[row.status]"
                >
                  {{ data.status[row.status] }}
                </q-item-label>
                <q-item-label caption>
                  {{ getStageName(row.chanceStage) }}
                </q-item-label>
              </q-item-section>
            </q-item>
            <q-separator inset />
            <q-card-section class="flex q-gutter-md">
              <div class="col-item">
                <q-item-label caption> 客户名称 </q-item-label>
                <q-item-label>
                  {{ row.customerName || "--" }}
                </q-item-label>
              </div>
              <div class="col-item">
                <q-item-label caption> 联系人 </q-item-label>
                <q-item-label>
                  {{ row.contactName || "--" }}
                </q-item-label>
              </div>
              <div class="col-item">
                <q-item-label caption> 联系电话 </q-item-label>
                <q-item-label>
                  {{ row.customerPhone || "--" }}
                </q-item-label>
              </div>
              <div class="col-item">
                <q-item-label caption> 需求ID </q-item-label>
                <q-item-label>
                  {{ row.demandId }}
                </q-item-label>
              </div>
              <div class="col-item">
                <q-item-label caption> 商机ID </q-item-label>
                <q-item-label>
                  {{ row.chanceId }}
                </q-item-label>
              </div>
              <div class="col-item">
                <q-item-label caption> 意向类型 </q-item-label>
                <q-item-label>
                  {{ row.intentionType || "--" }}
                </q-item-label>
              </div>
              <div class="col-item">
                <q-item-label caption> 跟进人 </q-item-label>
                <q-item-label>
                  {{ row.followerUserName || "--" }}
                </q-item-label>
              </div>
              <div class="col-item">
                <q-item-label caption> 最近跟进结果 </q-item-label>
                <q-item-label>
                  {{ data.followResult[row.followResult - 1] || "--" }}
                </q-item-label>
              </div>
              <div class="col-item">
                <q-item-label caption> 最近跟进时间 </q-item-label>
                <q-item-label>
                  {{ formatDate(row.followTime) }}
                </q-item-label>
              </div>
              <div class="col-item">
                <q-item-label caption> 预约跟进时间 </q-item-label>
                <q-item-label>
                  {{ row.appointmentTime || "--" }}
                </q-item-label>
              </div>

              <div class="col-item">
                <q-item-label caption> 商机来源 </q-item-label>
                <q-item-label>
                  {{ row.chanceSourceName || "--" }}
                </q-item-label>
              </div>
            </q-card-section>
            <q-separator inset />
            <q-item>
              <q-item-section></q-item-section>
              <q-item-section side>
                <q-btn
                  color="info"
                  icon="iconfont icon-message_fill_light"
                  label="在线联系"
                  unelevated
                  @click.stop="contactOnline(row)"
                />
              </q-item-section>
              <q-item-section side>
                <q-btn
                  color="blue"
                  icon="iconfont icon-phone"
                  label="电话联系"
                  unelevated
                  @click.stop="contactPhone(row)"
                />
              </q-item-section>
            </q-item>
          </q-card>
        </template>
      </div>
    </div>
    <div class="q-pa-md text-center" v-else>暂无数据</div>
    <div class="flex justify-center q-pa-md">
      <common-pagination
        v-model:page="data.pagination.page"
        :total="data.pagination.totalPage"
        v-if="data.pagination.totalPage > 1"
      ></common-pagination>
    </div>
  </q-page>
</template>
<style lang="scss" scoped>
.col-item {
  width: 160px;
}
</style>
<script>
import { date, useQuasar } from "quasar";
import {
  fetchChanceTypeCount,
  fetchChance,
  fetchStageList,
  fetchOrderCustomerInfo,
  fetchTargetIMInfo,
} from "src/assets/fetch";
import { parseCookie } from "src/assets/utils";
import CommonPagination from "src/components/CommonPagination.vue";
import ContactPhoneDialogVue from "src/components/dialogs/ContactPhoneDialog.vue";
import {
  defineComponent,
  reactive,
  watch,
  onUnmounted,
  inject,
  computed,
} from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

export default defineComponent({
  components: { CommonPagination },
  name: "PagesChancePageVue",
  setup() {
    const $q = useQuasar();
    const $store = useStore();
    const $router = useRouter();
    const bus = inject("bus");
    const changeAccount = (val) => (data.account.tab = val);
    const changeType = (val) => (data.type.tab = val);
    bus.on("changeAccountTab", changeAccount);
    bus.on("changeTypeTab", changeType);
    onUnmounted(() => {
      bus.off("changeAccountTab", changeAccount);
      bus.off("changeTypeTab", changeType);
    });
    const data = reactive({
      pagination: {
        page: 1,
        totalPage: 0,
        pageSize: 10,
      },
      account: {
        list: computed(() => $store.getters["persisted/accounts"] || []),
        tab: 0,
        value: computed(() => data.account.list[data.account.tab]),
      },
      type: {
        tab: 0,
        // 类型(0全部-默认 1今日需跟进 2待受理 3跟进中 4已结束 5已转化)
        opitons: [
          { label: "全部", name: 0, value: 0, key: "totalCount" },
          { label: "今日需跟进", name: 1, value: 0, key: "currentFollowCount" },
          { label: "待受理", name: 2, value: 0, key: "acceptCount" },
          { label: "跟进中", name: 3, value: 0, key: "followCount" },
          { label: "已结束", name: 4, value: 0, key: "doneCount" },
          { label: "已转化", name: 5, value: 0, key: "convertedCount" },
        ],
      },
      status: ["待分配", "待受理", "跟进中", "已转化", "已关闭"],
      chanceStage: [],
      followResult: ["意向度高", "中等意向", "意向度低", "无意向", "联系不上"],
      rows: [],
    });

    function refresh() {
      fetchChance(
        {
          type: data.type.tab,
          pageSize: data.pagination.pageSize,
          pageNum: data.pagination.page,
        },
        data.account.value.cookie
      ).then((res) => {
        data.rows = res.data || [];
        data.pagination.totalPage = res.totalPage;
      });
    }

    watch(() => data.pagination.page, refresh, { immediate: true });

    watch(
      () => [data.account.value, data.type.tab],
      (val, old) => {
        const [acc, type] = val;
        if (!!acc && acc != old[0]) {
          fetchChanceTypeCount(acc.cookie).then((res) => {
            data.type.opitons.forEach((el) => {
              el.value = res.data[el.key];
            });
          });
          fetchStageList(acc.cookie).then((res) => {
            data.chanceStage = res.data;
          });
        }
        if (acc != old[0] || type != old[1]) {
          refresh();
        }
      }
    );
    function formatDate(time, format = "YYYY-MM-DD HH:mm:ss") {
      if (!time) {
        return "--";
      }
      return date.formatDate(new Date(time), format);
    }

    return {
      data,
      formatDate,
      getStageName: function (e) {
        var t = data.chanceStage.length;
        return e && t
          ? (e > t && (e = t), data.chanceStage[e - 1].stageName)
          : "--";
      },
      open(row) {
        console.log(row);
        $router.push(
          `/detail/${row.demandId}?userid=${data.account.value.userid}`
        );
        // $router.push(
        //   `/browser/${data.account.value.userid}?url=https://jdyboss.zbj.com/chance/chance_detail?id=${row.chanceId}`
        // );
        // const cookies = parseCookie(data.account.value.cookie).data;
        // window.electron.openUrl(
        //   `https://jdyboss.zbj.com/chance/chance_detail?id=${row.chanceId}`,
        //   cookies
        // );
      },
      contactPhone(item) {
        $q.dialog({
          component: ContactPhoneDialogVue,
          componentProps: {
            chanceId: item.chanceId,
            customerId: item.customerId,
            cookie: data.account.value.cookie,
          },
        });
      },
      contactOnline(item) {
        fetchOrderCustomerInfo(item.customerId, data.account.value.cookie).then(
          (res) => {
            if (!res.data) {
              return;
            }
            fetchTargetIMInfo(
              {
                imKey: res.data.customerZbjIdImKey,
                chanceId: item.chanceId,
              },
              data.account.value.cookie
            ).then((res) => {
              const cookies = parseCookie(data.account.value.cookie).data;
              $router.push({
                path: "/server",
                query: {
                  id: cookies.userid,
                  key: res.data.webKey,
                },
              });
            });
          }
        );
      },
    };
  },
});
</script>
